#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/select.h>

int main(int argc, char const *argv[])
{
    if (argc != 2)
    {
        printf("Usage: %s <ip> <port>\n",argv[0]);
        return -1;
    }

    int server_socket = socket(AF_INET,SOCK_STREAM,0);
    if (server_socket == -1)
    {
        perror("socket err\n");
        return -1;
    }
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY;

    if (bind(server_socket,(struct sockaddr*)&addr,sizeof(addr))==-1)
    {
        perror("bind err\n");
        return -1;
    }

    if (listen(server_socket,5)==-1)
    {
        perror("listen err\n");
        return -1;
    }

    printf("wait client connect\n");
    int client_socket = -1;
    struct sockaddr_in client_addr;
    socklen_t client_addr_len =sizeof(client_addr);

    fd_set rdfds;
    fd_set tmpfds;
    int ret = -1;
    int clifd = -1;
    char buf[64] = {'\0'};

    FD_ZERO(&rdfds);
    FD_SET(server_socket,&rdfds);

    int maxfd =server_socket;
    while (1)
    {
        tmpfds = rdfds;

        ret = select(maxfd+1, &tmpfds,NULL,NULL,NULL);
        if (ret <0)
        {
            perror("select err\n");
            continue;
        }

        for (int i = 0; i < maxfd+1; i++)
        {
           if (FD_ISSET(i,&tmpfds))
           {
               if (i == server_socket)
               {
                   clifd = accept(server_socket,NULL,NULL);
                   printf("accept, clifd = %d\n",clifd);

                   FD_SET(clifd,&rdfds);
                   if (clifd > maxfd)
                   {
                       maxfd = clifd;
                   }
                   
               }
               else
               {
                    ret = recv(i,buf,64 ,0);
                    if (ret < 0)
                    {
                        perror("recv err\n");
                        continue;
                    }
                    else if (ret>0)
                    {
                        printf("clifd = %d buf = %s\n",i,buf);
                    }
                    else
                    {
                        printf("peer exit\n");
                        close(i);
                        FD_CLR(i,&rdfds);
                    }
               }   
           }  
        }
    }
    
    close(server_socket);

    return 0;
}
